using System.Security.Claims;
using BuildingBlocks.Abstractions.Permissions;
using Catalog.Application.Contracts;
using Microsoft.AspNetCore.Authorization;

namespace Catalog.HttpAPI.Permissions;

public class MixedPermissionHandler : AuthorizationHandler<PermissionRequirement>
{
    private readonly IPermissionCenterClient _permissionCenter;
    private readonly IRedisService _cache;

    public MixedPermissionHandler(IPermissionCenterClient permissionCenter, IRedisService cache)
    {
        _permissionCenter = permissionCenter;
        _cache = cache;
    }

    protected override async Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        PermissionRequirement requirement)
    {
        var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (string.IsNullOrEmpty(userId))
        {
            context.Fail();
            return;
        }

        // 1️⃣ 从缓存取绑定关系
        var bindings = await _cache.GetAsync<IReadOnlyCollection<PermissionBindingDto>>("Permission:CatalogService");
        var binding = bindings?.FirstOrDefault(b => b.resourceId == requirement.ResourceId);

        if (binding == null || string.IsNullOrEmpty(binding.resourceId))
        {
            // 没有定义或没有绑定资源 → 拒绝
            context.Fail();
            return;
        }

        // 2️⃣ 本地 Claims 检查
        if (context.User.HasClaim("permission", binding.permissionKey))
        {
            context.Succeed(requirement);
            return;
        }

        // 3️⃣ 权限中心兜底检查
        bool granted = await _permissionCenter.UserHasPermissionAsync(userId, binding.permissionKey);


        if (granted)
            context.Succeed(requirement);
        else
            context.Fail();
    }
}